var _util = require('util/util.js');
const { getServerURL, request } = require('../util/util');

var _account_service = {
    // xaxadwd
    checkLogin: function (resolve, reject) {
        // 检查本地存储中是否存在 token
        const token = localStorage.getItem('token'); // 或 sessionStorage
        const username = localStorage.getItem('username');
        if (token && username) {
            // 如果 token 存在，直接调用 resolve 表示已登录
            resolve({ isLoggedIn: true, token: token, username: username });
        } else {
            // 如果 token 不存在，调用 reject 表示未登录
            reject({ isLoggedIn: false });
        }
    },
    // 拉取当前用户详细信息
    getCurrentUserInfo: function (resolve, reject) {
        const token = localStorage.getItem('token');
        if (!token) {
            reject('未登录');
            return;
        }

        _util.request({
            url: _util.getServerURL('account/current'),
            method: "GET",
            headers: {
                'Authorization': 'Bearer ' + token
            },
            success: function (res) {
                if (res.status === 0) {
                    resolve(res); // res.data 包含详细信息
                } else {
                    reject(res.msg || '获取用户信息失败');
                }
            },
            error: function (err) {
                reject(err.message || '请求失败');
            }
        });
    },

    login: function (account, resolve, reject) {
        _util.request({
            url: _util.getServerURL('account/tokens'), // 后端接口路径
            data: JSON.stringify(account), // 转换为 JSON 格式
            method: "POST",
            contentType: "application/json", // 设置请求头
            success: function (resp) {
                if (resp.status === 0 && resp.extraData && resp.extraData.token) {
                    //成功获取token后保存到localStorage
                    localStorage.setItem('token', resp.extraData.token);
                    localStorage.setItem('username', account.username);
                    // 可以同时存储用户信息
                    localStorage.setItem('userInfo', JSON.stringify(resp.data));
                    // 获取上一页面URL并跳转
                    const lastPage = localStorage.getItem('lastPage');
                    if (lastPage) {
                        localStorage.removeItem('lastPage');
                        window.location.href = lastPage;
                    } else {
                        window.location.href = './catalog-main.html';
                    }
                    resolve(resp);
                } else {
                    reject(resp.msg || '登录失败');
                }
            },
            error: function (err) {
                reject(err.message || '请求失败');
            }
        });
    },
    loginByPhone: function (data, resolve, reject) {
        _util.request({
            url: _util.getServerURL('account/loginByPhone'),
            data: data,
            method: "POST",
            success: resolve,
            error: reject,

        });
    },
    sendCode: function (data, resolve, reject) {
        _util.request({
            url: _util.getServerURL('account/sendCode'),
            data: data,
            method: "GET",
            success: resolve,
            error: reject,

        });
    },


    logOut: function (resolve, reject) {
        const token = localStorage.getItem('token');
        const username = localStorage.getItem('username'); // 获取当前用户名
        if (!token || !username) {
            reject('未找到 Token 或用户信息');
            return;
        }

        _util.request({
            // ✅ 添加 username 到路径
            url: _util.getServerURL(`account/tokens/${username}`),
            method: "DELETE",
            headers: {
                'Authorization': 'Bearer ' + token
            },
            success: function (resp) {
                if (resp.status === 0) {
                    localStorage.removeItem('token');
                    localStorage.removeItem('username');
                    window.location.href = './account-login.html';
                    resolve(resp);
                } else {
                    reject(resp.msg || '退出失败');
                }
            },
            error: function (err) {
                if (err.status === 401) {
                    localStorage.removeItem('token');
                    localStorage.removeItem('username');
                    window.location.href = './account-login.html';
                }
                reject(err);
            }
        });
    },
    //注册
    signUp: function (account, resolve, reject) {
        _util.request({
            url: _util.getServerURL('account/accounts'),
            data: JSON.stringify(account), // 将数据序列化为 JSON
            method: "POST",
            contentType: "application/json", // 设置 Content-Type 为 JSON
            success: resolve,
            error: reject,
        });
    },
    // updatePassword: function (account, resolve, reject) {
    //     _util.request({
    //         url: _util.getServerURL('account/password_reset'),
    //         data: account,
    //         method: "POST",
    //         success: resolve,
    //         error: reject,
    //     })

    // },
    // update: function (account, resolve, reject) {
    //     _util.request({
    //         url: _util.getServerURL('account/update_info'),
    //         data: account,
    //         method: "POST",
    //         success: resolve,
    //         error: reject,
    //     })
    // },
    updateAll: function (account, resolve, reject) {
        const token = localStorage.getItem('token');
        if (!token) {
            reject("未登录");
            return;
        }
        // const username = account.username;
        // const updateInfo = () => {
        //     _util.request({
        //         url: _util.getServerURL(`account/${account.username}`), // 使用用户名作为路径参数
        //         data: account,
        //         method: "PUT",
        //         headers: {
        //             'Authorization': 'Bearer ' + token
        //         },
        //         contentType: "application/x-www-form-urlencoded",
        //         success: resolve,
        //         error: reject,
        //     });
        // }
        _util.request({
            url: _util.getServerURL(`account/${account.username}`),
            data: JSON.stringify(account),  // 🔥 转为 JSON 字符串
            method: "PUT",
            contentType: "application/json",
            headers: {
                'Authorization': 'Bearer ' + token
            },
            success: resolve,
            error: reject
        });

        // if (account.password) {
        //     // 包含密码时先更新密码
        //     _util.request({
        //         url: _util.getServerURL('account/password_reset'),
        //         data: {
        //             username: account.username,
        //             password: account.password
        //         },
        //         method: "POST",
        //         success: function () {
        //             // 密码更新成功后再更新其他信息
        //             updateInfo();
        //         },
        //         error: reject
        //     });
        // } else {
        //     // 没有密码直接更新资料
        //     updateInfo();
        // }
    }


};
module.exports = _account_service;